<template>
	<div id="app">
		<el-dialog title="用户注册" :visible.sync="dialogVisible" width="30%" @close="handleClose">
			<!-- 表单 -->
			<el-form
				label-position="left"
				:model="ruleForm"
				:rules="rules"
				ref="ruleForm"
				label-width="80px"
				class="demo-ruleForm"
			>
				<el-form-item label="头像" prop="avatar">
					<el-upload
						class="avatar-uploader"
						:action="uploadUrl"
						:data="uploadObj"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload"
					>
						<img v-if="imageUrl" :src="imageUrl" class="avatar" />
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="昵称" prop="name">
					<el-input v-model="ruleForm.name"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="ruleForm.email"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="phone">
					<el-input v-model="ruleForm.phone"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="ruleForm.password" show-password></el-input>
				</el-form-item>
				<el-row>
					<el-col :span="17">
						<el-form-item label="图形码" prop="code">
							<el-input v-model="ruleForm.code"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<img
							@click="refreshGraphicsCodeUrl"
							:src="graphicsCodeUrl"
							style="margin-left: 0px;"
							class="codeImg"
							alt=""
						/>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="17">
						<el-form-item label="验证码" prop="rcode">
							<el-input v-model="ruleForm.rcode"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="7">
						<el-button @click="getVcode" style="margin-left: 10px;">获取用户验证码</el-button>
					</el-col>
				</el-row>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button @click="submit" type="primary">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
	data() {
		// 自定义效验规则
		let verifiedEmail = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('邮箱不能为空'));
			}
			const reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
			if (!reg.test(value)) {
				callback(new Error('邮箱不合法'));
				return;
			}
			callback();
		};
		let verifiedPhone = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('手机号不能为空'));
			}
			const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
			if (!reg.test(value)) {
				callback(new Error('手机号不合法'));
				return;
			}
			callback();
		};
		let verifiedCode = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('图形码不能为空'));
			}
			if (value.toString().length != 4) {
				callback(new Error('图形码长度在 4 个字符'));
				return;
			}
			callback();
		};
		let verifiedRCode = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('验证码不能为空'));
			} else {
				if (value.toString().length != 4) {
					callback(new Error('验证码长度在 4 个字符'));
					return;
				}
				callback();
			}
		};
		// 数据
		return {
			dialogVisible: false, // 注册页面显示
			graphicsCodeUrl: process.env.VUE_APP_BASEURL + '/captcha?type=sendsms', // 图形码
			imageUrl: '', // 预览头像
			uploadObj: {}, // 上传头像的额外参数对象
			uploadUrl: process.env.VUE_APP_BASEURL + '/uploads', // 头像路径
			// 表单数据
			ruleForm: {
				avatar: '', // 头像上传后的地址
				name: '',
				email: '',
				phone: '',
				password: '',
				code: '',
				rcode: '',
				num: 0,
			},
			// 表单规则
			rules: {
				name: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
				email: [{ required: true, validator: verifiedEmail, trigger: 'blur' }],
				phone: [{ required: true, validator: verifiedPhone, trigger: 'blur' }],
				password: [
					{ required: true, message: '请输入密码', trigger: 'blur' },
					{ min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
				],
				code: [{ required: true, validator: verifiedCode, trigger: 'blur' }],
				rcode: [{ required: true, validator: verifiedRCode, trigger: 'blur' }],
			},
		};
	},
	methods: {
		// 图形码刷新
		refreshGraphicsCodeUrl() {
			this.graphicsCodeUrl = process.env.VUE_APP_BASEURL + '/captcha?type=sendsms' + Date.now();
		},
		// 获取手机验证码
		async getVcode() {
			let num = 0;
			this.$refs.ruleForm.validateField(['phone', 'code'], (errorMessage) => {
				if (!errorMessage) {
					num++;
				}
			});
			if (num === 2) {
				const res = await this.$axios.post('/sendsms', {
					phone: this.ruleForm.phone,
					code: this.ruleForm.code,
				});

				if (res.code === 200) {
					this.ruleForm.rcode = res.data.captcha;
				} else {
					this.$message({
						type: 'error',
						message: res.message,
						duration: 1000,
					});

					// 刷新图形码
					this.refreshGraphicsCodeUrl();
				}
			}
		},
		// 上传头像
		// 上传头像后
		handleAvatarSuccess(res, file) {
			this.imageUrl = URL.createObjectURL(file.raw);
		},
		// 上传头像前
		beforeAvatarUpload(file) {
			// 图片格式限制
			const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
			// 图片大小
			const isLt2M = file.size / 1024 / 1024 < 2;

			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPG|PNG|GIF 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}

			// 给上传头像添加额外参数(这个是后台要求的, 可以把后台打一顿), image属性是接口中规定的
			this.uploadObj.image = file;

			return isJPG && isLt2M;
		},
		// 注册提交功能
		submit() {
			this.$refs.ruleForm.validate(async (valid) => {
				if (!valid) {
					return;
				}
				const res = await this.$axios.post('/register', this.ruleForm);
				if (res.code === 200) {
					// 成功提示
					this.$message({
						type: 'success',
						message: '注册成功!',
						duration: 1000,
					});

					// 关闭弹窗
					dialogVisible = false;
				} else {
					// 错误提示
					this.$message({
						type: 'error',
						message: res.message,
						duration: 1000,
					});

					// 刷新图形码
					this.refreshGraphicsCodeUrl();
				}
			});
		},
		// 注册对话框清空内容
		handleClose() {
			this.$refs.ruleForm.resetFields();
			// 清空图片
			this.imageUrl = '';
		},
	},
};
</script>

<style lang="less">
.el-form-item__label {
	padding: 0;
}
.codeImg {
	width: 100%;
}
// 上传头像
.avatar-uploader {
	text-align: center;
}
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px !important;
	text-align: center;
}
.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>
